import {reactive} from 'vue'

// 播放器状态
const playerState = reactive({
    currentSong: null,
    playlist: [], // 播放列表
    currentIndex: -1, // 当前播放索引
    isPlaying: false,
    currentTime: 0,
    duration: 0,
    volume: 80,
    audioElement: null,
    progressUpdateCallback: null // 新增：进度更新回调
})

// 标准化歌曲数据格式
function normalizeSongData(song) {
    // 如果已经是标准格式，直接返回
    if (song.songName && song.artistName) {
        return song
    }

    // 处理喜欢页面的数据格式
    if (song.name) {
        return {
            ...song,
            songId: song.id || song.songId,
            songName: song.name,
            artistName: song.artistName,
            album: song.album,
            duration: song.duration,
            coverUrl: song.coverUrl,
            audioUrl: song.audioUrl,
            likeStatus: song.likeStatus,
            releaseTime: song.releaseTime
        }
    }

    // 默认返回原数据
    return song
}

// 初始化音频元素
function initAudioElement() {
    if (!playerState.audioElement) {
        playerState.audioElement = new Audio()

        playerState.audioElement.addEventListener('loadedmetadata', () => {
            playerState.duration = playerState.audioElement.duration
            console.log('音频时长:', playerState.duration)
        })

        playerState.audioElement.addEventListener('timeupdate', () => {
            playerState.currentTime = playerState.audioElement.currentTime
            // 调用进度更新回调
            if (playerState.progressUpdateCallback) {
                playerState.progressUpdateCallback(playerState.currentTime)
            }
        })

        playerState.audioElement.addEventListener('ended', () => {
            nextSong()
        })

        playerState.audioElement.addEventListener('error', (e) => {
            console.error('音频加载错误:', e)
        })

        playerState.audioElement.addEventListener('canplay', () => {
            console.log('音频可以播放')
        })

        playerState.audioElement.addEventListener('loadstart', () => {
            console.log('开始加载音频')
        })
    }
}

// 设置播放列表
function setPlaylist(playlist, currentIndex = 0) {
    // 标准化播放列表中的所有歌曲数据
    const normalizedPlaylist = playlist.map(song => normalizeSongData(song))
    playerState.playlist = normalizedPlaylist
    playerState.currentIndex = currentIndex
    console.log('设置播放列表:', normalizedPlaylist.length, '首歌曲，当前索引:', currentIndex)
}

// 播放歌曲
function playSong(song, playlist = null, index = 0) {
    try {
        // 标准化当前歌曲数据
        const normalizedSong = normalizeSongData(song)

        // 如果有传入播放列表，则设置播放列表
        if (playlist && Array.isArray(playlist)) {
            setPlaylist(playlist, index)
        }

        // 如果没有播放列表，但当前有播放列表，尝试在现有列表中查找歌曲
        if (!playlist && playerState.playlist.length > 0) {
            const songIndex = playerState.playlist.findIndex(s =>
                s.songId === normalizedSong.songId || s.id === normalizedSong.id
            )
            if (songIndex !== -1) {
                playerState.currentIndex = songIndex
            } else {
                // 如果歌曲不在播放列表中，添加到列表末尾
                playerState.playlist.push(normalizedSong)
                playerState.currentIndex = playerState.playlist.length - 1
            }
        }

        // 如果没有播放列表且当前也没有播放列表，创建新的播放列表
        if (!playlist && playerState.playlist.length === 0) {
            playerState.playlist = [normalizedSong]
            playerState.currentIndex = 0
        }

        playerState.currentSong = normalizedSong
        playerState.isPlaying = true

        initAudioElement()

        if (normalizedSong.audioUrl) {
            playerState.audioElement.src = normalizedSong.audioUrl
            playerState.audioElement.load()

            playerState.audioElement.play().catch(error => {
                console.error('播放失败:', error)
                playerState.isPlaying = false
            })
        } else {
            console.warn('歌曲没有音频URL:', normalizedSong)
            playerState.isPlaying = false
        }

        console.log('开始播放:', normalizedSong.songName, '索引:', playerState.currentIndex, '播放列表长度:', playerState.playlist.length)

    } catch (error) {
        console.error('播放歌曲时发生错误:', error)
        playerState.isPlaying = false
    }
}

// 切换播放状态
function togglePlay() {
    if (!playerState.audioElement) return

    if (playerState.isPlaying) {
        playerState.audioElement.pause()
    } else {
        playerState.audioElement.play().catch(error => {
            console.error('播放失败:', error)
        })
    }
    playerState.isPlaying = !playerState.isPlaying
}

// 下一首
function nextSong() {
    if (playerState.playlist.length === 0) return

    let nextIndex = playerState.currentIndex + 1
    if (nextIndex >= playerState.playlist.length) {
        nextIndex = 0 // 循环播放
    }

    console.log('下一首，当前索引:', playerState.currentIndex, '下一首索引:', nextIndex)

    const nextSong = playerState.playlist[nextIndex]
    if (nextSong) {
        playSong(nextSong, playerState.playlist, nextIndex)
    }
}

// 上一首
function prevSong() {
    if (playerState.playlist.length === 0) return

    let prevIndex = playerState.currentIndex - 1
    if (prevIndex < 0) {
        prevIndex = playerState.playlist.length - 1 // 循环播放
    }

    console.log('上一首，当前索引:', playerState.currentIndex, '上一首索引:', prevIndex)

    const prevSong = playerState.playlist[prevIndex]
    if (prevSong) {
        playSong(prevSong, playerState.playlist, prevIndex)
    }
}

// 跳转到指定时间
function seek(time) {
    if (playerState.audioElement) {
        playerState.audioElement.currentTime = time
        playerState.currentTime = time
    }
}

// 设置音量
function setVolume(volume) {
    playerState.volume = volume
    if (playerState.audioElement) {
        playerState.audioElement.volume = volume / 100
    }
}

// 设置进度更新回调
function setProgressUpdateCallback(callback) {
    playerState.progressUpdateCallback = callback
}

// 移除进度更新回调
function removeProgressUpdateCallback() {
    playerState.progressUpdateCallback = null
}

// 格式化时间（秒转换为分:秒）
function formatTime(seconds) {
    if (!seconds || isNaN(seconds)) return '0:00'

    const mins = Math.floor(seconds / 60)
    const secs = Math.floor(seconds % 60)
    return `${mins}:${secs.toString().padStart(2, '0')}`
}

export function usePlayer() {
    return {
        playerState,
        playSong,
        togglePlay,
        nextSong,
        prevSong,
        seek,
        setVolume,
        formatTime,
        setPlaylist,
        setProgressUpdateCallback,
        removeProgressUpdateCallback,
        normalizeSongData
    }
}